import React, { useState, useEffect, useRef } from 'react'
import "./myscss/Setup.scss"
import { ActionSheet, Cell, Toast } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000';

export default function Setup() {
    let navigate = useNavigate()
    const [sxtzt, setsxtZt] = useState(false)
    const actions = [{ name: '拍照' }, { name: '本地选择' }];
    const [zt, setzt] = useState(false)
    //摄像头
    const cameraVideoRef = useRef(null);
    const cameraCanvasRef = useRef(null);

    function successFunc(mediaStream) {
        const video = cameraVideoRef.current;
        // const video = document.getElementById('cameraVideo') as HTMLVideoElement;
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in video) {
            video.srcObject = mediaStream;
        }
        video.onloadedmetadata = () => {
            video.play();
        };
    }

    function errorFunc(err) {
        console.log(`${err.name}: ${err.message}`);
        // always check for errors at the end.
    }
    // 启动摄像头
    const openMedia = () => { // 打开摄像头
        const opt = {
            audio: false,
            video: {
                width: 100,
                height: 100
            }
        };
        navigator.mediaDevices.getUserMedia(opt).then(successFunc).catch(errorFunc);
    };
    // 关闭摄像头
    const closeMedia = () => {
        // const video = document.getElementById('cameraVideo') as HTMLVideoElement;
        const video = cameraVideoRef.current;
        const stream = video.srcObject;
        if ('getTracks' in stream) {
            const tracks = stream.getTracks();
            tracks.forEach(track => {
                track.stop();
            });
            video.srcObject = null;

        }
        setsxtZt(false)
    };
    const getImg = () => {
        // const video = document.getElementById('cameraVideo') as HTMLVideoElement;
        // const canvas = document.getElementById('cameraCanvas') as HTMLCanvasElement;
        const video = cameraVideoRef.current;
        const canvas = cameraCanvasRef.current;
        if (canvas == null) {
            return;
        }
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); // 把视频中的一帧在canvas画布里面绘制出来
        const imgStr = canvas.toDataURL(); // 将图片资源转成字符串
        const base64Img = imgStr.split(';base64,').pop(); // 将图片资源转成base64格式
        const imgData = {
            base64Img
        };
        // closeMedia(); // 获取到图片之后可以自动关闭摄像头
        return imgData;
    };
    // console.log(getImg()); 
    const saveImg = () => {
        // 获取图片数据
        const data = getImg();
        // 设置图片标签的源为获取到的 base64 图片数据
        const imgTag = document.getElementById('imgTag');
        if (imgTag) {
            imgTag.src = data.base64Img;
        }
        // 使用更现代的方法创建 a 标签并设置其属性
        const saveLink = document.createElement('a');
        saveLink.href = data.base64Img;
        saveLink.download = 'i.png';

        
        // 模拟点击事件
        saveLink.click();
        
    };




    const [uploading, setUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [selectedImage, setSelectedImage] = useState(null);
    const handleImageUpload = async () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.onchange = async (e) => {
            const file = e.target.files[0];
            if (file) {
                setSelectedImage(file);
                setUploading(true);
                const formData = new FormData();
                formData.append('image', file);
                try {
                    await axios.post('http://localhost:3000/upload', formData, {

                    });
                    console.log('图片上传成功');
                } catch (error) {
                    console.error('图片上传失败', error);
                } finally {
                    setUploading(false);
                }
            }
        };
        input.click();
    };


    let click = async (val) => {
        if (val.name === '拍照') {
            openMedia()
            setsxtZt(true)
            setzt(false)
        } else if (val.name === '本地选择') {
            handleImageUpload()
            setzt(false)
        }

    }
    return (
        <div id='Setup'>
            <div className='fans_length'>
                <b onClick={() => { navigate('/mine') }}>&lt;</b><span>设置</span>
            </div>
            <div className='center'>
                <div className='first'>
                    <div>头像</div>
                    <div className='pai'>
                        <Cell isLink onClick={() => setzt(true)} />
                        <ActionSheet
                            cancelText="取消"
                            visible={zt}
                            onCancel={() => setzt(false)}
                            actions={actions}
                            onSelect={(val) => { click(val) }}
                        />
                    </div>
                </div>
                <div className='first'>
                    <div>修改手机号</div>
                    <div>
                        <Cell isLink onClick={() => navigate('/MinPage/Phone')} />

                    </div>
                </div>
                <div className='first'>
                    <div>修改密码</div>
                    <div>
                        <Cell isLink onClick={() => navigate('/MinPage/Mima')} />
                    </div>
                </div>
                <div className='first'>
                    <div>清除缓存</div>
                    <div>
                        <Cell isLink onClick={() => { Toast.info({ message: '清除完成' }); }} />

                    </div>
                </div>
                <div className='first'>
                    <div>检查更新</div>
                    <div>
                        <Cell isLink onClick={() => { Toast.info({ message: '当前是最新版本' }); }} />
                    </div>
                </div>
                <div className='first'>
                    <div>推送设置</div>
                    <div>
                        <Cell isLink />

                    </div>
                </div>
            </div>
            <button type="primary">退出登录</button>
            <div className='sxt'>
                {/* 摄像头 */}
                {
                    sxtzt ?
                        <>
                            <div>
                                <video
                                    id="cameraVideo"
                                    ref={cameraVideoRef}
                                    style={{
                                        height: '100px', width: '100px'
                                    }}
                                />
                                <canvas
                                    id="cameraCanvas"
                                    ref={cameraCanvasRef}
                                    width={100}
                                    height={100}
                                    style={{
                                        width: '100px', height: '100px'
                                    }}
                                />

                                <button onClick={() => { openMedia() }} >打开摄像头</button>
                                <button onClick={() => { saveImg() }} >保存</button>
                                <button onClick={() => { closeMedia() }} >关闭摄像头</button>
                            </div>

                        </> : <></>
                }
            </div>
        </div>
    )
}
